package com.example.fresheveryday.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.java_websocket.WebSocket;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.fresheveryday.po.User;
import com.example.fresheveryday.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Component
@Slf4j

@ServerEndpoint("/websocket/{username}")
@RestController
@RequestMapping("/socket")
public class WebsocketController {
    /**
     * 记录当前在线连接数
     */
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();
    public List<User> userList = null;
    private static UserService userService;
    @Autowired
    public void setMyServiceImpl(UserService userService){
        //WebSocket为当前webSocket的类
        WebsocketController.userService = userService;
    }
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        sessionMap.put(username, session);
        log.info("有新用户加入，username={}, 当前在线人数为：{}", username, sessionMap.size());
        System.out.println("userId" + username + "加入");
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("id",username);
        User user = userService.getOne(wrapper);
        System.out.println(user);

    }
    @RequestMapping("/getOnlineUserList")
    public List<User> get(){
        return this.userList;
    }
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("username") String username){
        JSONObject obj = JSON.parseObject(message);
        String toUsername = obj.getString("to");
        String from = obj.getString("from");
        String message1 = obj.getString("message");
        String pic = obj.getString("pic");

        Session tosession = sessionMap.get(toUsername);

        if (tosession!=null){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message",message1);
            jsonObject.put("from", from);
            jsonObject.put("pic", pic);
            this.sendMessage(jsonObject.toString(), tosession);
        }
        System.out.println(message);
    }
    /**
     * 服务端发送消息给客户端
     */
    private void sendMessage(String message, Session toSession) {
        try {
            log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), message);
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败", e);
        }
    }


}
